{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Making footprint scenarios using Python\n",
    "\n",
    "Author: <a href=\"mailto:a.owen@leeds.ac.uk\"> Dr Anne Owen </a> \n",
    "\n",
    "Before we start, paste the following code into the box below:\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import copy\n",
    "pd.options.display.precision = 2\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this tutorial we are going to use a real world multiregional input-output database: The World Input Output Database (WIOD).\n",
    "\n",
    "A first version of the World Input-Output Database was constructed within the official WIOD Project, funded by the European Commision as part of the 7th Framework Programme, Theme 8: Socio-Economic Sciences and Humanities. This project ran from May 2009 and ended in April 2012. The database was offically launched on April 16, 2012 in Brussels.\n",
    "\n",
    "A second, updated version of WIOD was launched in 2016. This is the version we will be using but I have aggregated some of the countries together to make it faster to run. \n",
    "\n",
    "The modified WIOD contains 28 countries, an aggregated rest of EU region and an aggregated Rest of World region for the period 2000-2014. Data for 56 sectors are classified according to the International Standard Industrial Classification revision 4 (ISIC Rev. 4).\n",
    "\n",
    "## Exercise 1.1 Make the total footprint function\n",
    "\n",
    "Copy this function into the box below:\n",
    "\n",
    "```python\n",
    "def total_footprint_calc(Z,Y,y_region,f):   \n",
    "    x = np.sum(Z,1) + np.sum(Y,1)\n",
    "    x[x==0] = 0.000000001\n",
    "    big_X = np.tile(np.transpose(x),[30*56,1])\n",
    "    A = Z/big_X \n",
    "    L = np.linalg.inv(np.identity(30*56)-A)\n",
    "    e = f/x \n",
    "    eL = np.dot(e,L)\n",
    "    footprint_by_region = np.dot(eL,y_region)\n",
    "\n",
    "    return footprint_by_region\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You should notice there are few differences to the function you worked with in the previous exercise.\n",
    "\n",
    "We have a new line:\n",
    "\n",
    "```python\n",
    "x[x==0] = 0.000000001\n",
    "```\n",
    "\n",
    "In WIOD, there are a few sectors in some countries where output is zero. The country has no industry of that type in its economy. So, when we calculate ```A```, we would be dividing by zero which would cause an error.\n",
    "\n",
    "What we are doing with this line of code is replacing any zeros with a tiny number so that we don't get errors.\n",
    "\n",
    "Also notice that when we tile ```x``` to make ```big_X``` we repeat it ```30*56``` times. $30$ x $56$ is $1680$. The Z matrix in WIOD has $1680$ rows and columns. And we know this because WIOD has $30$ regions each with $56$ sectors.\n",
    "\n",
    "When we calculate ```footprint_by_region``` we sum the array. This is to ensure that we get a float type result, rather than an array. We are doing this because we are going to use this later on."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise 1.2: Load the data\n",
    "\n",
    "WIOD has data for 14 years. We need to think about how to store this. We have worked with 2D DataFrames but for each of our variables, we are going to need a DataFrame for each year.\n",
    "\n",
    "In python we can make something called a dictionary which is a collection of DataFrames. We can then specify which year we are interest in by writing ```Z[2000]``` for example.\n",
    "\n",
    "Before we can load the data we must set up some empty dictionaries. Write:\n",
    "\n",
    "```python\n",
    "Z = {}\n",
    "Y = {}\n",
    "f = {}\n",
    "fhh = {}\n",
    "```\n",
    "\n",
    "You should have an idea what ```Z```, ```Y``` and ```f``` contain. We'll cover ```fhh``` later."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Each individual year of data for each of ```Z```, ```Y``` and ```f``` is contained in a csv file.\n",
    "\n",
    "The country name and sector names are found in the first column and row of the ```Z``` files.\n",
    "\n",
    "The country names are found in the first row of the ```Y``` files and the country name and sector names are found in the first column of the ```Y``` files.\n",
    "\n",
    "The country name and sector names are found in the first row of the ```f``` files.\n",
    "\n",
    "Try the following code:\n",
    "\n",
    "```python\n",
    "for yr in range (2000,2015):\n",
    "    print(yr)\n",
    "    Z[yr] = pd.read_csv('WIODv2016_data/z_' +str(yr)+ '.csv', header=0,index_col=0)\n",
    "    Y[yr] = pd.read_csv('WIODv2016_data/y_' +str(yr)+ '.csv', header=0,index_col=0)\n",
    "    f[yr] = np.transpose(pd.read_csv('WIODv2016_data/f_' +str(yr)+ '.csv', header=0,index_col=0))\n",
    "    fhh[yr] = pd.read_csv('WIODv2016_data/fhh_' +str(yr)+ '.csv', header=0,index_col=0)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's take a closer look at what it is doing.\n",
    "\n",
    "First, it makes a 'for-loop' which cycles through the years 2000 to 2016 (remember in Python, when you specify a range, the end is always the number after you want to stop!)\n",
    "\n",
    "This loop is creating a variable called ```year```\n",
    "\n",
    "The second line of code prints the year. This is an entirely unnessessary peice of code but I put it in here to demonstrate what ```year``` is and to let you know that something was happening. If the line was not there it would not be obvious that anything had happened!\n",
    "\n",
    "Now, imagine we are in our first loop. ```year = 2000```. The next line is therefore going to place something in a dataframe called ```Z[2000]``` and the data it is loading in is in the file ```2000_Z.csv```\n",
    "\n",
    "Notice how the code updates the name of the file from the variable year on each loop?\n",
    "\n",
    "Try having a look at the data by selecting:\n",
    "\n",
    "```python\n",
    "pd.set_option('display.max_columns', 100)\n",
    "display(Z[2000])\n",
    "```\n",
    "Note that we have forced python to show more columns than usual"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise 1.3 Trying out the function with WIOD - The UK's footprint in 2000\n",
    "\n",
    "Let's use the ```total_footprint_calc``` funtction to find the footprint of the United Kingdom for the year 2000. To do this, we can call the function and pass it the following parameters:\n",
    "\n",
    "```python\n",
    "Z[2000]\n",
    "Y[2000]\n",
    "Y[2000].loc[:,'GBR']\n",
    "f[2000]\n",
    "```\n",
    "    \n",
    "Notice how rather than make ```y_region```, we can use ```Y[2000].loc[:,'GBR']``` as a short cut.\n",
    "\n",
    "Try\n",
    "\n",
    "```python\n",
    "total_footprint_calc(Z[2000],Y[2000],Y[2000].loc[:,'GBR'],f[2000])\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is telling us that the carbon footprint in the UK in 2000 was 604,081 kilotonnes. If you work it out on a per person basis, this is around 8 tonnes per person. \n",
    "\n",
    "The actual carbon footprint is a little higher because we also need to add in the emissions that households generate themselves from burning fuel to heat their homes and run power cars. This forms a separate account and we have it stored in the file ```2000_fhh.csv```. \n",
    "\n",
    "Let's take a look at that file. Try\n",
    "\n",
    "```python\n",
    "display(fhh[2000])\n",
    "```\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### You should see that UK households burnt 149330 kilotonnes CO2 in the year 2000 from heating their homes and using fuel in their cars.\n",
    "\n",
    "We need to adjust the ```total_footprint_calc``` function to include these 'direct' emissions from households. Remake your function below.\n",
    "\n",
    "```python\n",
    "def total_footprint_calc2(Z,Y,y_region,f,fhh):   \n",
    "    x = np.sum(Z,1) + np.sum(Y,1)\n",
    "    x[x==0] = 0.000000001\n",
    "    big_X = np.tile(np.transpose(x),[30*56,1])\n",
    "    A = Z/big_X \n",
    "    L = np.linalg.inv(np.identity(30*56)-A)\n",
    "    e = f/x \n",
    "    eL = np.dot(e,L)\n",
    "    footprint_by_region = np.sum(np.sum(np.dot(eL,y_region),0,0) + np.sum(fhh,0)\n",
    "\n",
    "    return footprint_by_region\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "try\n",
    "\n",
    "```python\n",
    "total_footprint_calc2(Z[2000],Y[2000],Y[2000].loc[:,'GBR'],f[2000],f[2000].loc['GBR'])\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we have included direct emissions from household's we find the UK's footprint is 753,411 kilotonnes CO2. Now let's make a timeseries for all the years. \n",
    "\n",
    "## Exercise 1.4 Using a for-loop to find the UK footprint for the years 2000 to 2014\n",
    "\n",
    "First let's create a varaible years that contains the range 2000-2014\n",
    "\n",
    "```python\n",
    "    years = range(2000,2015)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we will set up a new empty variable called data which will hold the carbon footprint for the years 2000 to 2014. Try:\n",
    "\n",
    "```python\n",
    "    data = np.zeros((15,1))\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we are going to set up a for-loop to call the function for every year in years. We will put the result into our data variable. The problem is that we will need to tell Python which cell to put the result in. This is where the enumerate function becomes really useful. Enumerate will count how many times we have looped through the function and we can use it to decide which cell to fill.\n",
    "\n",
    "Try:\n",
    "\n",
    "```python\n",
    "for count, yr in enumerate(years):\n",
    "    print[yr]\n",
    "    data[count,0] = total_footprint_calc2(Z[yr],Y[yr],Y[yr].loc[:,'GBR'],f[yr],fhh[yr].loc['GBR'])\n",
    "        \n",
    "UK_foot = pd.DataFrame(data,index=years)\n",
    "UK_foot\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Try\n",
    "```python\n",
    "chart = UK_foot.plot( kind = 'line')\n",
    "chart.set_ylabel('kilotonnes CO2')\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What happened in 2007-2009 to cause the massive drop in the UK's consumption-based emissions?\n",
    "\n",
    "## Exercise 1.5 Comparing the UK's production- and consumption-based emissions for the years 2000 to 2014\n",
    "\n",
    "Now try:\n",
    "\n",
    "```python\n",
    "data = np.zeros((15,2))\n",
    "years = range(2000,2015)\n",
    "count = 0\n",
    "for count, yr in enumerate(years):\n",
    "    industry_emissions = np.sum(np.sum(f[yr].loc[:,'GBR Crop and animal production, hunting and related service activities':'GBR Activities of extraterritorial organizations and bodies'],0),0)\n",
    "    hhold_direct = np.sum(fhh[yr].loc['GBR'],0)\n",
    "    data[count,0] = industry_emissions + hhold_direct\n",
    "UK_emissions = pd.DataFrame(data,index = years,columns=['Production','Consumption'])\n",
    "UK_emissions['Consumption'] = UK_foot\n",
    "UK_emissions\n",
    "```\n",
    "\n",
    "Notice that we have reset count to be zero before using it again. \n",
    "\n",
    "Notice too how we have found the UK's production emissions by adding up the industrial emissions in $f$ that cover the sectors 'Crop and animal production, hunting and related service activities' to 'GBR Activities of extraterritorial organizations and bodies'.\n",
    "\n",
    "Finally, notice that rather than recalculating the consumption emissions, we have simply put the previously calculated data into this new UK_emissions dataframe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Try plotting a line graph of the UK's production and consumption emissions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise 1.6 Comparing the consumption-based emissions of all the regions in WIOD\n",
    "\n",
    "Can you use the ```total_footprint_calc``` function to put the footprint of each of the 30 regions, for the year 2014, into a dataframe called region_foot?\n",
    "\n",
    "You will need to change the size of 'data' and make a variable called 'regions' which contains the country codes. \n",
    "\n",
    "Do this by\n",
    "\n",
    "```python\n",
    "data = np.zeros((30,1))\n",
    "regions = Y[2014].columns\n",
    "```\n",
    "\n",
    "Think carefully about how you will change the set up of the for-loop:\n",
    "\n",
    "```python\n",
    "for count, yr in enumerate(years):\n",
    "```\n",
    "\n",
    "What will you use instead of ```yr``` in ```years```?\n",
    "\n",
    "Think carefully about how you will change ```y_region```. What will you use instead of:\n",
    "\n",
    "```python\n",
    "Y[yr].loc[:,'GBR']\n",
    "```\n",
    "\n",
    "Remember to change both ```yr``` and ```'GBR'```\n",
    "    \n",
    "your last two lines should be:\n",
    "\n",
    "```python\n",
    "region_foot = pd.DataFrame(data,index = regions)\n",
    "region_foot\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now try\n",
    "```python\n",
    "chart = region_foot.plot( kind = 'bar')\n",
    "chart.set_ylabel('kilotonnes CO2')\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise 1.7 Comparing the production- and consumption-based emissions of all the regions in WIOD\n",
    "\n",
    "Try writing code that will generate a dataframe showing production- and consumption-based emissions for the year 2014 for each country in the WIOD database.\n",
    "\n",
    "The tricky bit here is the labels for the industrial emissions. For the first country, you would want to find the sum of numbers between 'AUS Agriculture, Hunting, Forestry and Fishing' and 'AUS Private Households with Employed Persons'. Then for the second country, this is the sum of numbers between 'AUT Agriculture, Hunting, Forestry and Fishing' and 'AUT Private Households with Employed Persons'.\n",
    "\n",
    "We can use the ```reg``` variable to help here.\n",
    "\n",
    "The key line of code is:\n",
    "\n",
    "```python\n",
    "industry_emissions = np.sum(np.sum(f[2014].loc[:,reg+' Crop and animal production, hunting and related service activities':reg+' Activities of extraterritorial organizations and bodies'],0),0)\n",
    "```\n",
    "    \n",
    "Notice how reg+ is used.\n",
    "\n",
    "Try and write the complete set of code to make the new 'region_emissions' dataframe with two columns (production and consumption) rather than one."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Can you generate this chart?\n",
    "\n",
    "<img src=\"https://github.com/earao/images/blob/main/Screenshot%202023-12-22%20at%2015.31.18.png?raw=true\" width = 500, height = 500/>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise 2.1 Setting up a series of scenarios to model the effect of Brexit on the UK's consumption-based emissions\n",
    "\n",
    "In this set of exercises we are going to model five different futures for the United Kingdom:\n",
    "\n",
    "Option A - is a business as usual scenario where in 2030, the UK looks the same as it did in 2014\n",
    "\n",
    "Option B - demonstrates economic growth after brexit and the UK's final demand is at 2007 levels\n",
    "\n",
    "Option C - is a new trade deal scenario where the UK buys fewer goods from Germany and France and doubles trade with China\n",
    "\n",
    "Option D - is a green new deal scenario where the UK decarbonises its power sector \n",
    "\n",
    "Option E - is a global green new deal scenario where the UK sells its power technology to China\n",
    "\n",
    "We will generate a function which, when passed the parameters ```Z```,```Y```,```y_region```,```f``` and ```fhh``` will return a dataframe which shows the UK total footprint, the consumption emissions that are emitted domestically and the consumption emissions that are emitted abroad (the imported emissions).\n",
    "\n",
    "Paste the following code into the box below:\n",
    "\n",
    "```python\n",
    "def scenario_footprint_calc(Z,Y,y_region,f,fhh):\n",
    "    data = np.zeros((3,1))\n",
    "    x = np.sum(Z,1) + np.sum(Y,1)\n",
    "    x[x==0] = 0.000000001\n",
    "    big_X = np.tile(np.transpose(x),[1435,1])\n",
    "    A = Z/big_X \n",
    "    L = np.linalg.inv(np.identity(1435)-A)\n",
    "    e = f/x \n",
    "    eL = np.dot(e,L)\n",
    "    temp = np.dot(np.dot(np.diagflat(e.values),L),np.diag(y_region))\n",
    "    footprint_full = pd.DataFrame(temp,index = Z.index,columns=Y.index)\n",
    "    hhold_direct = np.sum(fhh,0)\n",
    "    data[0,0] = np.sum(np.sum(footprint_full,0),0)+hhold_direct\n",
    "    data[1,0] = np.sum(np.sum(footprint_full.loc['GBR Crop and animal production, hunting and related service activities':'GBR Activities of extraterritorial organizations and bodies',:],0),0)+hhold_direct\n",
    "    data[2,0] = data[0,0]-data[1,0]\n",
    "    \n",
    "    scenario = pd.DataFrame(data,index=(['Total Footprint','Domestic emissions','Imported emissions']))\n",
    "    \n",
    "    return scenario\n",
    "```\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Most of this code should be familiar to you now. But let's look at the lines which populate the variable ```data``` a little more closely.\n",
    "\n",
    "The first item in data ```(data[0,0])``` is the total footprint. This is calculated by finding the sum of the entire result matrix which is called ```footprint_full```. Remember this is a matrix with the row headings as the source industries and the column headings as the final products. We also add on the UK emissions from households burning fuel themselves.\n",
    "\n",
    "The second item in data ```(data[1,0])``` is the domestic emissions. Here we are looking to add up the emissions that are emitted in the UK to meet UK demand. These must be those that are sourced in the UK. Notice that the code looks for the rows that start with 'GBR', but takes every column (using the : symbol). We also add on the UK emissions from households burning fuel themselves because these have to be domestic emissions emitted within the UK boundary.\n",
    "\n",
    "The third item in data ```(data[2,0])``` is the imported emissions. This is simply going to be the difference between the total footprint and the domestic emissions.\n",
    "\n",
    "## Exercise 2.2 Scenario A - business as usual\n",
    "\n",
    "Try this\n",
    "\n",
    "```python\n",
    "ScenarioA = scenario_footprint_calc(Z[2014],Y[2014],Y[2014].loc[:,'GBR'],f[2014],fhh[2014].loc['GBR'])\n",
    "ScenarioA\n",
    "```\n",
    "    \n",
    "to generate a dataframe of results for Scenario A. Inside the ```()``` note that you have passed the parameters ```Z,Y,y_region,f``` and ```fhh```  for the year 2009 and ```y_region``` refers to the UK.\n",
    "\n",
    "Retyping ```ScenarioA``` allows us to look at the result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise 2.3 Scenario B - economic growth\n",
    "\n",
    "Use the format\n",
    "```python\n",
    "ScenarioB = scenario_footprint_calc()\n",
    "ScenarioB\n",
    "```\n",
    "    \n",
    "to generate a dataframe of results for Scenario B. In this case, keep  ```Z[2014]```,```Y[2014]```,```f[2014]``` and ```fhh[2014]``` but look at the effect of the UK spend being at 2007 (the highest) levels."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise 2.4 Scenario C - growth and a new trade deal\n",
    "\n",
    "In this scenario, the UK has 2007 levels of spend but imports from different places. We create a new ```y_region``` parameter by making a copy of ```Y``` and editing it. First try:\n",
    "\n",
    "```python\n",
    "    YC = copy.deepcopy(Y)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the 2007 layer of ```YC``` we want the UK to spend differently on products from Germany (half of original), France (half of original) and China (double of original)\n",
    "\n",
    "To edit ```YC``` for the UK's spend on German goods in 2007, we use:\n",
    "\n",
    "```python\n",
    "    YC[2007].loc['DEU Crop and animal production, hunting and related service activities':'DEU Activities of extraterritorial organizations and bodies','GBR'] = Y[2007].loc['DEU Crop and animal production, hunting and related service activities':'DEU Activities of extraterritorial organizations and bodies','GBR']*0.5\n",
    "```\n",
    "    \n",
    "Notice how you are identifying the cells in the UK column but the rows for Germany.\n",
    "\n",
    "Can you follow this format to change the spend on French goods (FRA) to half the 2009 spend and the spend on Chinese goods (CHN) to double the 2009 spend? Don't forget to also include the German line of code from above!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Run Scenario C using your new version of ```YC``` for the ```y_region``` parameter:\n",
    "\n",
    "```python\n",
    "ScenarioC = scenario_footprint_calc(Z[2014],Y[2014],YC[2007].loc[:,'GBR'],f[2014],fhh[2014].loc['GBR')\n",
    "ScenarioC\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You should have found that compared to Scenario B, the new trade deal increases emissions.\n",
    "\n",
    "Interestingly, domestic emissions reduce slightly. This is because there are a small amount of UK emissions that make up the supply chain of goods that we import. These are reimported emissions! And we trade a lot with the France and Germany so reducing this trade means that UK industries don't need to make as many parts that are used in the production of the French and German goods that are bought by the UK.\n",
    "\n",
    "Clearly there are issues with the realism of our scenarios. We don't know if this simple switch is replacing like for like goods. You can try a more detailed change in the UK final demand vector another time.\n",
    "\n",
    "## Exercise 2.5 Scenario D - green new deal\n",
    "\n",
    "In this scenario we will reduce the industrial emissions associated with the ```Electricity, gas, steam and air conditioning supply``` sector to zero.\n",
    "\n",
    "To do this, make a deep copy of ```f```, call it ```fD```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next locate ```GBR Electricity, gas, steam and air conditioning supply``` for the year 2014 in your new ```fD``` and make it equal zero.\n",
    "\n",
    "Try\n",
    "```python\n",
    "fD[2014]['GBR Electricity, gas, steam and air conditioning supply']=0\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now create ```ScenarioD``` which uses ```fD[2014]``` and the rest are all at the 2014 levels"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Compare your results to Scenario A. You should find a large reduction in the emissions sourced from the UK but no change to the imported emissions.\n",
    "\n",
    "## Exercise 2.6 Scenario E - global green new deal\n",
    "\n",
    "In this scenario we will reduce the industrial emissions associated with China's Electricity, Gas and Water Supply sector to the level of UK's sector from Scenario D.\n",
    "\n",
    "Try coding this. Remember that ```fE``` is a deepcopy of ```fD``` and the country code for China is ```CHN```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Create ```ScenarioE```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now you should find domestic emissions to be the same level as Scenario D but imports have reduced."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise 2.7 Scenario F - new trade deal and a global new deal\n",
    "\n",
    "Now use ```YC[2007]``` and ```fE[2014]``` to create a final scenario which changes both the final demand levels in the UK and alters the industrial emissions intensity. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Excercise 2.8 Consolidate the scenarios into one data frame and make a new row for percent change\n",
    "\n",
    "Let's put all the scenario data into a single dataframe. To do this, we can use the ```concat``` function. We need to list the names of the dataframes we want to combine together and tell python what dimension (axis) to combine them in. If we use 0, they will be put into a long vertical list. If we use 1 they will be lined up horizontally.\n",
    "\n",
    "Try\n",
    "\n",
    "```python\n",
    "scenarios = pd.concat([ScenarioA,ScenarioB,ScenarioC,ScenarioD,ScenarioE,ScenarioF],axis=1)\n",
    "scenarios.columns = ['Scenario A','Scenario B','Scenario C','Scenario D','Scenario E','Scenario F']\n",
    "scenarios\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now lets calculate the percentage change from 2014 as a new line in our dataframe.\n",
    "\n",
    "Try\n",
    "\n",
    "```python\n",
    "scenarios.loc['Percent change from 2014'] = scenarios.loc['Total Footprint']/scenarios.loc['Total Footprint','Scenario A']*100-100\n",
    "scenarios\n",
    "```\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Which scenario brings about the greatest increase in emissions?\n",
    "\n",
    "Which scenario reduces emissions by the most?\n",
    "\n",
    "Can you try to reproduce the two charts below?\n",
    "\n",
    "<img src=\"https://github.com/earao/images/blob/main/Screenshot%202023-12-22%20at%2015.33.28.png?raw=true\" width=500 height=500 />\n",
    "\n",
    "<img src=\"https://github.com/earao/images/blob/main/Screenshot%202023-12-22%20at%2015.34.40.png?raw=true\" width=500 height=500/>\n",
    "\n",
    "HINT 1: The command ```np.transpose``` will transpose your table (make the rows become columns).\n",
    "\n",
    "HINT 2: Think about how to isolate the parts of the table you want to show"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Key learning points\n",
    "You should have learnt:\n",
    "<ol>\n",
    "<li>How to load data into python from a csv file</li>\n",
    "<li>How to update variable names in a for loop e.g. load files for different years</li>\n",
    "<li>How to calculate consumption and production acounts from the WIOD database for different years and different countries</li>\n",
    "<li>How set up a simple scenario that changes industrial emissions intensities and final demand spends</li>\n",
    "<li>How to interpret the results of your scenario</li>\n",
    "   \n",
    "</ol>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
